<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.order_no"
          placeholder="编号查询"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="负责人查询"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getAllData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="应缴开始日期"
          end-placeholder="应缴结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumCheckStatus"
          v-model="params['check_status.eq']"
          @change="getAllData()"
          clearable
          placeholder="核算状态"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getAllData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="dialogImportVisible = true" icon="el-icon-upload2">导入</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          type="primary"
          :loading="exportLoading"
          @click="exportExcel()"
        >
          导出
        </el-button>
      </el-form-item>
      <div class="text-muted" v-loading="countLoading2">
        项目数量：
        <span class="text-primary">{{ relatedCount || '-' }}</span>
        。订单条数：
        <span class="text-primary">{{ totalCount || '-' }}</span>
      </div>
    </el-form>

    <c-table
      @sort-change="handleSortChange"
      border
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
    >
      <template v-slot:checkStatus="scope">
        <div :class="['text-wrapper', `text-${scope.row.checkStatusStyle}`]">
          <div>{{ scope.row.checkStatusLabel }}</div>
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <edit-dialog
      :visible.sync="editVisible"
      :edit-row="editRow"
      :view-mode="editViewMode"
      @success="getData(params.index)"
    ></edit-dialog>

    <import-excel
      :excel-template="importFileUrl"
      title="导入保费"
      :post-api="postUrl"
      :visible.sync="dialogImportVisible"
      @success="getData()"
    ></import-excel>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { lastPickerShortcuts, nextPickerShortcuts } from '@/common/plugins/tools/date'
import {
  enumCheckStatus,
  enumCheckStatusStyle,
  CheckStatus,
} from '@/bigcredit/views/settle/accounting/model'

import SelectAddress from '@/components/select/SelectAddress'
import EditDialog from '@/bigcredit/views/settle/accounting/EditDialog'
import { exportTable } from '@/bank/plugins/export'
import ImportExcel from '@/components/ImportExcel'
import { queryTrouble } from '@vimi/utils-api'

export default {
  components: {
    SelectAddress,
    EditDialog,
    ImportExcel,
  },
  data() {
    const h = this.$createElement
    return {
      enumCheckStatus,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        corp_name: '',
        address_code: '',
        order_no: '',
        'check_status.eq': '',
        'gua_type.eq': '',
        'service_id.eq': '',
      },
      loading: false,
      tableName: 'credit_warrant_fee_record_view_db',
      tableData: [],
      totalCount: 0,
      order: {
        N1check_status: 'asc',
        N2due_warrant_date: 'asc',
      },

      isNear: false,
      datePicked: [],

      tableColumns: [
        { attrs: { label: '序号', prop: 'index', align: 'center' } },
        { attrs: { label: '订单编号', prop: 'order_no', minWidth: 150, sortable: 'order_no' } },
        {
          attrs: {
            label: '项目名称',
            prop: 'customer_name',
            minWidth: '120px',
            sortable: 'customer_name',
          },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address', minWidth: 150 }, truncate: 2 },
        {
          attrs: {
            label: '负责人',
            prop: 'corp_name',
            align: 'center',
            sortable: 'corp_name',
            width: 110,
          },
        },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center', width: '120px' } },
        {
          attrs: {
            label: '在保余额(万元)',
            prop: 'left_funds',
            align: 'right',
            sortable: 'left_funds',
          },
        },
        { attrs: { label: '担保费率(%)', prop: 'gua_rate', align: 'right', sortable: 'gua_rate' } },
        {
          attrs: {
            label: '缴费金额(万元)',
            prop: 'actual_warrant_fee',
            align: 'right',
            sortable: 'actual_warrant_fee',
          },
        },
        {
          attrs: {
            label: '应缴时间',
            prop: 'dueWarrantDate',
            align: 'center',
            minWidth: 100,
            sortable: 'due_warrant_date',
          },
        },
        {
          attrs: {
            label: '银行机构',
            prop: 'bank_name',
            align: 'center',
            sortable: 'bank_name',
            minWidth: 110,
          },
          truncate: 2,
        },
        {
          attrs: {
            label: '核算状态',
            prop: 'checkStatusLabel',
            align: 'center',
            width: 110,
            sortable: 'check_status',
          },
          slot: 'checkStatus',
        },
        {
          attrs: { label: '项目经理', prop: 'res_a_name', align: 'center', width: 100 },
          process: (v, row) => ({
            attr: { class: 'text-sm' },
            value: [
              h('small', `A角:${v || '-'}`),
              h('br'),
              h('small', `B角:${row.res_b_name || '-'}`),
            ],
          }),
        },
        {
          attrs: { label: '操作', align: 'center', minWidth: 130 },
          operations: [
            {
              content: '去核算',
              icon: 'fa fa-gavel',
              event: this.handleEdit,
              ifRender: r =>
                r.checkStatus === CheckStatus.Undo && [r.res_a, r.res_b].includes(this.userId),
            },
            {
              content: '核算确认',
              icon: 'fa fa-gavel',
              event: this.handleEdit,
              ifRender: r => r.checkStatus === CheckStatus.ToConfirm && this.isFinanceUser,
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.hanleView,
            },
          ],
        },
      ],

      pickerOptions: {
        shortcuts: [...lastPickerShortcuts, ...nextPickerShortcuts],
      },

      // 编辑
      editRow: {},
      editVisible: false,
      editViewMode: false,

      exportLoading: false,
      countLoading2: false,
      relatedCount: '',
      dialogImportVisible: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'userId']),
    isFinanceUser() {
      return this.user.scopeArr.includes('financeO')
    },
    importFileUrl() {
      return `//attach.qedan.com/template/保费导入模板.xlsx?${+new Date()}`
    },
    postUrl() {
      return (
        '/api/credit/import/' +
        queryTrouble('credit_warrant_fee_record', {
          importKey: 'credit_warrant_fee_record_template',
          'service_id.eq': this.clientId,
        })
      )
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.params['service_id.eq'] = this.clientId
    this.getAllData()
  },
  methods: {
    getAllData() {
      this.getData()
      this.getCountCustomer()
    },
    getCountCustomer() {
      this.countLoading2 = true
      this.$api
        .getData(this.$serviceName, this.tableName, {
          ...this.params,
          index: 1,
          size: 1,
          groupFields: 'customer_related_id',
        })
        .then(res => {
          this.relatedCount = res?.data?.totalCount ?? 0
        })
        .finally(() => {
          this.countLoading2 = false
        })
    },
    handleSortChange({ order, column }) {
      if (!order) {
        this.order = { N1check_status: 'asc', N2due_warrant_date: 'asc' }
      } else {
        this.order = {}
        this.order[column.sortable] = order.includes('asc') ? 'asc' : 'desc'
      }
      this.getData()
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, this.order)
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    dataAdapter(row, index) {
      row.index = this.totalCount - index - this.params.size * (this.params.index - 1)
      row.dueWarrantDate = this.$utils.dateFormat(row.due_warrant_date, 'yyyy-MM-dd') || '-'
      row.checkStatus = +(row.check_status || 0)
      row.checkStatusLabel = enumCheckStatus[row.checkStatus]
      row.checkStatusStyle = enumCheckStatusStyle[row.checkStatus]
      row.checkStatusSubLabel = ''

      return row
    },
    handleEdit(row = {}) {
      this.editViewMode = false
      this.editRow = row
      this.editVisible = true
    },
    hanleView(row = {}) {
      this.editViewMode = true
      this.editRow = row
      this.editVisible = true
    },
    handleDateChange() {
      this.params.index = 1
      this.resetParams()
      if (this.datePicked && this.datePicked.length === 2) {
        this.params['due_warrant_date.gte'] = this.datePicked[0]
        this.params['due_warrant_date.lte'] = `${this.datePicked[1]} 23:59:59`
      }
      this.getAllData()
    },
    resetParams() {
      this.params['check_status.in'] = ''
      this.params['check_status.eq'] = ''
      this.params['due_warrant_date.gt'] = ''
      this.params['due_warrant_date.gte'] = ''
      this.params['due_warrant_date.lte'] = ''
      this.params['due_warrant_date.lt'] = ''
    },

    exportExcel() {
      this.exportLoading = true
      exportTable({
        columns: this.tableColumns,
        table: this.tableName,
        params: this.params,
        order: this.order,
        adapter: this.dataAdapter,
        filename: '保费核算',
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
</script>
<style lang="scss" scoped></style>
